package com.twt.recruit.controller;

import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.twt.recruit.entity.Club;
import com.twt.recruit.entity.ClubMember;
import com.twt.recruit.entity.User;
import com.twt.recruit.mapper.ClubMapper;
import com.twt.recruit.mapper.ClubMemberMapper;
import com.twt.recruit.mapper.UserMapper;
import com.twt.recruit.service.FileService;
import com.twt.recruit.service.ProjectService;
import com.twt.recruit.service.UserService;
import com.twt.recruit.utils.JwtTokenUtils;
import com.twt.recruit.utils.response.CommonEnum;
import com.twt.recruit.utils.response.ResultBody;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;


@RestController
@Tag(name="用户")
@RequestMapping("/v1")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    UserMapper userMapper;

    @Resource
    ClubMapper clubMapper;
    @Resource
    ClubMemberMapper clubMemberMapper;

    @Resource
    FileService fileService;

    @Resource
    ProjectService projectService;

    @Resource
    UserService userService;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @PostMapping(value = "/user/login")
    @Operation(summary = "登录")
    public ResultBody login(@RequestParam String account,
                            @RequestParam String password) {
        try {
            //组织账号
            QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", account);
            Club club = clubMapper.selectOne(queryWrapper);
            if (club!=null){
                if (bCryptPasswordEncoder.matches(password, club.getPassword())){
                    JSONObject re = JSONUtil.parseObj(club);
                    String role = "ROLE_ORGAN";
                    if (Objects.equals(club.getName(), "管理")){
                        role = "ROLE_ADMIN";
                    }
                    re.putOpt("token",JwtTokenUtils.TOKEN_PREFIX+JwtTokenUtils.createToken("", club.getClubId(), role, true));
                    re.remove("password");
                    if (re.getInt("scale")==0){
                        re.putOpt("accountType",2);
                    }
                    if (re.getInt("scale")==1){
                        re.putOpt("accountType",3);
                    }
                    return ResultBody.success(re);
                }else {
                    return ResultBody.error(CommonEnum.PASSWORD_ERROR);
                }
            }

            //个人账号
            Map<String, Object> paramMap = new HashMap<>();

            paramMap.put("account", account);
            paramMap.put("password", password);


            HttpRequest loginRequest = HttpRequest.post("https://api.twt.edu.cn/api/auth/common")
                    .header("domain", "weipeiyang.twt.edu.cn")
                    .header("ticket", "YmFuYW5hLjM3YjU5MDA2M2Q1OTM3MTY0MDVhMmM1YTM4MmIxMTMwYjI4YmY4YTc=")
                    .header("Cookie", "JSESSIONID=824387D685F213C214C3E1A67F68DF64")
                    .form(paramMap);

            JSONObject body = JSONUtil.parseObj(loginRequest.execute().body(), JSONConfig.create().isIgnoreNullValue());
            ResultBody demo = new ResultBody();
            demo.setCode(String.valueOf(body.getInt("error_code")));
            demo.setMessage(body.getStr("message"));
            demo.setResult(body.get("result"));
            User user = new User();
            if (Objects.equals(demo.getMessage(), "成功")){
                ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
                JSONObject tmp = JSONUtil.parseObj(body.get("result"));
                String uid = tmp.getStr("userNumber");
                String name = tmp.getStr("realname");
                tmp.remove("userNumber");
                tmp.remove("realname");
                tmp.putOpt("uid", uid);
                tmp.putOpt("name", name);
                tmp.putOpt("avatar", null);
                user = converterRegistry.convert(User.class, tmp);
                user.setAvatar("/default.jpg");
                if (userMapper.selectById(user.getUid())==null){
                    userMapper.insert(user);
                }else{
                    userMapper.updateById(user);
                }
            }else {
                return demo;
            }
            JSONObject r = JSONUtil.parseObj(user);
            r.putOpt("accountType", 1);
            r.putOpt("token",JwtTokenUtils.TOKEN_PREFIX+JwtTokenUtils.createToken(user.getUid(), null, "ROLE_USER", true));
            return ResultBody.success("success", r);
        } catch (Exception e) {
            logger.error("登陆失败", e);
            return ResultBody.error("登录失败");
        }
    }

    @PostMapping("/admin/import")
    @Operation(summary = "管理员导入社团")
    public ResultBody importOrgan(@Parameter(description = "默认密码首字母小写，天外天工作室->twtgzs1h") @RequestParam List<String> clubNames,
                                  @Parameter(description = "0:院级;1:校级") @RequestParam Integer scale){
        try {
            int repeat = 0;
            int count = 0;
            for (String c: clubNames){
                LambdaQueryWrapper<Club> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Club::getName, c);
                if (clubMapper.selectList(queryWrapper).size()==1){
                    repeat++;
                    continue;
                }
                Club club = new Club();
                club.setName(c);
                club.setScale(scale);
                club.setAvatar("/default.jpg");
                club.setPassword(bCryptPasswordEncoder.encode(PinyinUtil.getFirstLetter(c, "")));
                clubMapper.insert(club);
                count++;
            }
            return ResultBody.success("重复:"+repeat+"|成功:"+count);
        }catch (Exception e){
            logger.error("导入组织失败", e);
            return ResultBody.error("导入失败");
        }
    }

    @PostMapping("/organ/avatar")
    @Operation(summary = "上传组织头像")
    public ResultBody uploadOrganAvatar(@RequestParam MultipartFile avatar,
                                        @RequestHeader(JwtTokenUtils.TOKEN_HEADER) String token){
        try {
            String filePath = fileService.upload(avatar);
            UpdateWrapper<Club> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("club_id",JwtTokenUtils.getClubHttp(token)).set("avatar", filePath);
            clubMapper.update(null, updateWrapper);
            return ResultBody.success(filePath);
        }catch (Exception e){
            logger.error("上传失败", e);
            return ResultBody.error("上传失败", e);
        }

    }


    @PostMapping("/user/avatar")
    @Operation(summary = "上传个人头像")
    public ResultBody uploadUserAvatar(@RequestParam MultipartFile avatar,
                                       @RequestHeader(JwtTokenUtils.TOKEN_HEADER) String token){
        try {
            String filePath = fileService.upload(avatar);
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("uid",JwtTokenUtils.getUserNumberHttp(token)).set("avatar", filePath);
            userMapper.update(null, updateWrapper);
            return ResultBody.success(filePath);
        }catch (Exception e){
            logger.error("上传失败", e);
            return ResultBody.error("上传失败");
        }

    }

    @GetMapping("/user/organs")
    @Operation(summary = "获取用户参加的社团")
    public ResultBody getUserOrgans(@RequestHeader(JwtTokenUtils.TOKEN_HEADER) String token){
        try {
            String uid = JwtTokenUtils.getUserNumberHttp(token);
            return ResultBody.success(userService.getUserOrgans(uid));
        }catch (Exception e){
            logger.error("获取社团失败", e);
            return ResultBody.error("获取社团失败");
        }
    }


    @GetMapping("/user/token")
    @Operation(summary = "获取个人token")
    public ResultBody getUserToken(@RequestParam(required = false) Integer clubId,
                                   @RequestHeader(JwtTokenUtils.TOKEN_HEADER) String t){
        try {
            String uid = JwtTokenUtils.getUserNumberHttp(t);
            String role = "ROLE_USER";
            if (clubId!=null){
                LambdaQueryWrapper<ClubMember> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ClubMember::getClubId, clubId);
                queryWrapper.eq(ClubMember::getUid, uid);
                ClubMember clubMember = clubMemberMapper.selectOne(queryWrapper);
                if (clubMember!=null){
                    role = clubMember.getRole();
                }
            }
            String token = JwtTokenUtils.TOKEN_PREFIX+JwtTokenUtils.createToken(uid, clubId, role, true);
            return ResultBody.success(token);
        }catch (Exception e){
            logger.error("获取个人token失败", e);
            return ResultBody.error("获取个人token失败");
        }

    }

    @GetMapping("/user/info")
    @Operation(summary = "获取个人信息")
    public ResultBody getUserDetails(@RequestHeader(JwtTokenUtils.TOKEN_HEADER) String header){
        try {
            String uid = JwtTokenUtils.getUserNumberHttp(header);
            System.out.println(uid);
            JSONObject info = JSONUtil.parseObj(userMapper.selectById(uid));
            info.putOpt("organs", userService.getUserOrgans(uid));
            return ResultBody.success(info);
        }catch (Exception e){
            logger.error("获取个人信息失败", e);
            return ResultBody.error("获取个人信息失败");
        }
    }

    @Operation(summary = "初始化")
    @PostMapping("/user/init")
    public ResultBody init(@RequestParam String code){
        if (Objects.equals(code, "PVjYyYGsrDyPV8UK7uha")){
            Club club = new Club();
            club.setName("管理");
            club.setScale(1);
            club.setAvatar("/default.jpg");
            club.setPassword(bCryptPasswordEncoder.encode("PVjYyYGsrDyPV8UK7uha"));

            return ResultBody.success(clubMapper.insert(club));
        }else {
            return ResultBody.success();
        }

    }

//    @Operation(summary = "获取项目招募时间")
//    @GetMapping("/user/project/date")
//    public ResultBody getRecruitDate(@RequestParam Integer projectId){
//        List<String> recruitDate = projectService.getRecruitDate(projectId);
//
//        if (recruitDate == null) {
//            return ResultBody.error("获取招募时间失败");
//        }
//
//        return ResultBody.success("获取成功", recruitDate);
//    }

}

